package com.poker.wiki.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.poker.common.utils.CopyUtil;
import com.poker.common.utils.SnowFlake;
import com.poker.wiki.Service.CategoryService;
import com.poker.wiki.entity.Category;
import com.poker.wiki.entity.CategoryExample;
import com.poker.wiki.mapper.CategoryMapper;
import com.poker.wiki.req.CategoryQueryReq;
import com.poker.wiki.req.CategorySaveReq;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;

    @Resource
    SnowFlake snowFlake;

    @Override
    public List<Category> getAllCategory() {
        CategoryExample example = new CategoryExample();
        example.setOrderByClause(" sort asc ");

        return categoryMapper.selectByExample(null);
    }

    @Override
    public void delete(Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(category.getId())) {
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        } else {
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    @Override
    public PageInfo<Category> findCategory(CategoryQueryReq req) {
        CategoryExample example = new CategoryExample();
        CategoryExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%"+req.getName()+"%");
        }

        PageHelper.startPage(req.getPageNum(),req.getPageSize());
        List<Category> categoryList = categoryMapper.selectByExample(example);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        return pageInfo;
    }
}
